package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    //查询全部方法
    //@RequiredPermission(name = "权限列表",expression = "permission:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo pageResult = permissionService.query(qo);
        model.addAttribute("pageResult", pageResult);
        return "permission/list";
    }

    //处理删除请求
    //@RequiredPermission(name = "权限删除",expression = "permission:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                permissionService.deleteByPrimaryKey(id);
            }
            return new JsonResult(true,"删除成功");
        }catch (Exception e){
            return new JsonResult(false,"删除失败");
        }
    }

    //新增 或 修改
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            //表示去修改
            Permission permission = permissionService.selectByPrimaryKey(id);
            model.addAttribute("permission", permission);
        }
        return "permission/input";// 让 浏览器重新 发一次请求 跳转到input 页面
    }

    // 新增 或 修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission) {

        if (permission.getId() != null) {
            //新增
            permissionService.updateByPrimaryKey(permission);
        } else {
            permissionService.insert(permission);
        }
        return "redirect:/permission/list.do";
    }
    //@RequiredPermission(name="权限加载",expression = "permission:reload")
    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult reload() {
        try {
            permissionService.reload();
            return new JsonResult(true,"加载成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"加载失败");
        }
    }



}
